package com.config;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entry.Member;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class Loginlnterceptor implements HandlerInterceptor {


    /*
     * 此方法再控制器的方法执行之前进行拦截，可以做登录检查，权限判断等
     *
     * return boolean 返回boolean类型
     * 1. true 说明满足条件，放行
     * 2.false 说明不满足条件，不放行。同时开始自己编写调转到登录页面，没有权限访问提示页面等
     *
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //从session获取登录储存User对象
        Member member = (Member) request.getSession().getAttribute("member");
        System.out.println("member:"+member);
        if (member == null) {
            //跳转页面
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }

        return true;
    }


    /*
     * 此方法是后续处理方法，再控制器方法执行完毕以后执行，可以记录操作日志等
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        Member member = (Member) request.getSession().getAttribute("member");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(date);
        System.out.println(member.getMember_name()+"在"+currentTime+",做了"+handler+"操作");
    }

    /*
     *此方法再视图渲染完毕以后执行，可以释放资源等操作
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}




